import { useCallback, useRef, useState, useEffect } from "react";
import { notification, message } from "antd";
import type { Color } from "antd/es/color-picker";
import {
  saveSpecificUserConfig,
  getFullUserConfig,
  CONFIG_TYPES,
  saveTextColors,
  saveAnimationSettings,
  UserConfig,
} from "@/utils/helpers";

export type AutoSaveStatus = "idle" | "saving" | "saved";

interface ConfigManagerProps {
  userId: string;
  onStatusChange: (status: AutoSaveStatus) => void;
}

export const useConfigManager = ({
  userId,
  onStatusChange,
}: ConfigManagerProps) => {
  const saveTimeoutRef = useRef<NodeJS.Timeout>();
  const autoSaveStatusRef = useRef<NodeJS.Timeout>();
  const [configLoaded, setConfigLoaded] = useState(false);

  // 显示自动保存提示
  const showAutoSaveNotification = useCallback(
    (configType: string) => {
      onStatusChange("saved");

      // 清除之前的状态重置定时器
      if (autoSaveStatusRef.current) {
        clearTimeout(autoSaveStatusRef.current);
      }

      // 3秒后重置状态
      autoSaveStatusRef.current = setTimeout(() => {
        onStatusChange("idle");
      }, 3000);
    },
    [onStatusChange],
  );

  // 获取配置类型中文名称
  const getConfigTypeName = (configType: string): string => {
    const typeNames: { [key: string]: string } = {
      [CONFIG_TYPES.PROJECT_NAME]: "项目名称",
      [CONFIG_TYPES.CANVAS]: "画布",
      [CONFIG_TYPES.TEXT_BASIC]: "文本基本",
      [CONFIG_TYPES.TEXT_BORDER]: "文本边框",
      [CONFIG_TYPES.TEXT_BACKGROUND]: "文本背景",
      [CONFIG_TYPES.TEXT_ANIMATION]: "文本动画",
      [CONFIG_TYPES.VIDEO_MATERIALS]: "视频素材",
      [CONFIG_TYPES.TEXT_COLORS]: "文本颜色",
      [CONFIG_TYPES.ANIMATION_SETTINGS]: "动画设置",
    };
    return typeNames[configType] || "配置";
  };

  // 防抖保存配置函数
  const debouncedSaveConfig = useCallback(
    (configType: string, configData: any) => {
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }

      // 设置保存中状态
      onStatusChange("saving");

      saveTimeoutRef.current = setTimeout(async () => {
        const success = await saveSpecificUserConfig(
          userId,
          configType,
          configData,
        );
        if (success) {
          console.log(`${configType} 配置已自动保存`);
          showAutoSaveNotification(configType);
        } else {
          onStatusChange("idle");
          notification.error({
            message: "自动保存失败",
            description: `${getConfigTypeName(
              configType,
            )} 配置保存失败，请重试`,
            placement: "topRight",
            duration: 3,
          });
        }
      }, 1000); // 1秒防抖
    },
    [userId, showAutoSaveNotification, getConfigTypeName, onStatusChange],
  );

  // 保存文本颜色配置
  const saveTextColorsConfig = useCallback(
    (
      textColor: Color | string,
      borderColor: Color | string,
      backgroundColor: Color | string,
    ) => {
      const textColorStr =
        typeof textColor === "string" ? textColor : textColor.toHexString();
      const borderColorStr =
        typeof borderColor === "string"
          ? borderColor
          : borderColor.toHexString();
      const backgroundColorStr =
        typeof backgroundColor === "string"
          ? backgroundColor
          : backgroundColor.toHexString();

      onStatusChange("saving");

      const saveColorConfig = async () => {
        const success = await saveTextColors(
          userId,
          textColorStr,
          borderColorStr,
          backgroundColorStr,
        );
        if (success) {
          showAutoSaveNotification(CONFIG_TYPES.TEXT_COLORS);
        } else {
          onStatusChange("idle");
          notification.error({
            message: "自动保存失败",
            description: "文本颜色配置保存失败，请重试",
            placement: "topRight",
            duration: 3,
          });
        }
      };

      // 防抖延迟执行
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
      saveTimeoutRef.current = setTimeout(saveColorConfig, 1000);
    },
    [userId, showAutoSaveNotification, onStatusChange],
  );

  // 加载已保存的配置
  const loadSavedConfigs: () => Promise<VideoProjectConfig | null> =
    useCallback(async () => {
      try {
        const savedConfig = await getFullUserConfig(userId);
        if (savedConfig && Object.keys(savedConfig).length > 0) {
          message.success("已加载保存的配置");
          setConfigLoaded(true);
          return savedConfig;
        } else {
          setConfigLoaded(true);
          return null;
        }
      } catch (error) {
        message.error("加载配置失败");
        setConfigLoaded(true);
        return null;
      }
    }, [userId]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
      if (autoSaveStatusRef.current) {
        clearTimeout(autoSaveStatusRef.current);
      }
    };
  }, []);

  return {
    configLoaded,
    debouncedSaveConfig,
    saveTextColorsConfig,
    loadSavedConfigs,
  };
};
